<template>
    <el-tabs type="card" class="demo-tabs" v-model="ActiveTab.name" @tab-click="changeTab" closable
        @tab-remove="removeTab">
        <!-- name是双向绑定的名称 label是显示的名字 -->
        <el-tab-pane v-for="tab in tabList" :key="tab.url" :label="tab.name" :name="tab.name">
            <template #label>
                <span class="custom-tabs-label">
                    <el-icon>
                        <component :is="tab.icon"></component>
                    </el-icon>
                    <span>{{ tab.name }}</span>
                </span>
            </template>
        </el-tab-pane>
    </el-tabs>
    <RouterView v-slot="{Component}">
        <KeepAlive>
            <component :is="Component" :key="$route.name" v-if="$route.meta.keepAlive"></component>
        </KeepAlive>
        <component :is="Component" :key="$route.name" v-if="!$route.meta.keepAlive"></component>
    </RouterView>
</template>


<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { useTabsStore } from '@/store/tabs';
import { useRouter,useRoute } from 'vue-router';
import { useUserStore } from '@/store/auth';
const tabsStore = useTabsStore()
const { tabList, ActiveTab } = storeToRefs(tabsStore)
const { setActiveTab,removeTabs,addTab } = tabsStore

const userStore = useUserStore()
const {menu} = storeToRefs(userStore)
const router = useRouter()
const route = useRoute()
// 页面加载的时候默认的一个tab
function findObjectById(arr:any[],url:string){
    for(const item of arr){
        if(item.url===url){
            return item
        }
        if(item.children){
            const found:any = findObjectById(item.children,url)
            if(found){
                return found
            }
        }
    }
    return null
}
const {name,icon,url} = findObjectById(menu.value,route.path)
addTab(name,icon,url)
setActiveTab(name,url)
// 点击标签页进行跳转
const changeTab = ({ index }: { index: number }) => {
    router.push(tabList.value[index]?.url as string)
    setActiveTab(tabList.value[index]?.name as string, tabList.value[index]?.url as string)
}
// 删除标签
const removeTab = (name:any)=>{
    removeTabs(name)
    router.push(ActiveTab.value.url)
}
</script>

<style lang="less" scoped>
::v-deep .is-active {
    background-color: #227eff;
    color: white;

}
</style>